package channel

import (
	"context"

	v1 "caas-platform-payment/api/channel/v1"
	"caas-platform-payment/internal/consts"
	"caas-platform-payment/internal/dao"
	"caas-platform-payment/internal/model/do"

	"gitee.com/liangziyisheng/caas-platform-mc/utility/utils"
	"github.com/gogf/gf/v2/errors/gerror"
)

func (c *ControllerV1) Add(ctx context.Context, req *v1.AddReq) (res *v1.AddRes, err error) {
	// return nil, gerror.NewCode(gcode.CodeNotImplemented)
	// tenantCode := ctx.Value(consts.TokenClaims.TenantCode).(string)
	in := &do.PayChannel{}
	utils.CopyStruc(&req, in)
	in.EnableFlag = "Y" // 新增商户默认是启用的
	// 检查支付渠道名称是否允许
	contains := false
	for _, v := range consts.PayChannels {
		if v.Name == in.ChannelName {
			contains = true
			break
		}
	}
	if !contains {
		return nil, gerror.NewCode(consts.PayChannelNameNotExist)
	}
	in.PayNotifyUrl = "/api/payment/" + req.ChannelName + "/paynotify/" + req.TenantCode + "/" + req.AppId
	in.RefundNotifyUrl = "/api/payment/" + req.ChannelName + "/refundnotify/" + req.TenantCode + "/" + req.AppId
	id, err := dao.PayChannel.Ctx(ctx).InsertAndGetId(in)
	if err != nil {
		l.Error(ctx, err)
		return nil, gerror.NewCode(consts.AddFailed)
	}
	return &v1.AddRes{Id: id}, nil
}
